package spike.s001.builders.list.builders.service;

import org.apache.log4j.Logger;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.*;

/**
 * Created by ylyang on 29/03/2017.
 */
public class PeopleBuilderWithList {
    private static Logger logger = Logger.getLogger(PeopleBuilderWithList.class);

    List<String> columns = new ArrayList<>();
    List<Object> values = new ArrayList<>();
    List<String> questionMarks = new ArrayList<>();

    public PeopleBuilderWithList() {
        setColumnValue("NAME", UUID.randomUUID());
        setColumnValue("AGE", (new Random()).nextInt(100));
        setColumnValue("GENDER", randomFrom(new String[]{"Man", "Woman"}));
        setColumnValue("ROLE", randomFrom(new String[]{"Dev", "BA", "QA", "RM", ""}));
    }

    public void setColumnValue(String column, Object value) {
        int cIndex = columns.indexOf(column);
        if (cIndex >= 0) {
            columns.remove(cIndex);
            values.remove(cIndex);
            questionMarks.remove(cIndex);
        }

        if (value != null) {
            columns.add(column);
            values.add(value);
            questionMarks.add("?");
        }
    }

    public PeopleBuilderWithList name(String name) {
        setColumnValue("NAME", name);

        return this;
    }

    public PeopleBuilderWithList age(int age) {
        setColumnValue("AGE", age);

        return this;
    }

    public PeopleBuilderWithList gender(String gender) {
        setColumnValue("GENDER", gender);

        return this;
    }

    public PeopleBuilderWithList role(String role) {
        setColumnValue("ROLE", role);

        return this;
    }

    public void build(JdbcTemplate jdbcTemplate) {
        String sqlLine = String.format("INSERT INTO PEOPLE(%s) VALUES(%s)",
                String.join(",", columns),
                String.join(",", questionMarks)
        );

        jdbcTemplate.update(sqlLine, values.toArray());

        logger.info(sqlLine + " --> OK");
    }

    private static String randomFrom(String[] a) {
        int x = (new Random()).nextInt(a.length);
        return a[x];
    }
}
